<?php

class FileDownload {
	public static function downloadFile($rq_file_name, $sub_folder = "")
	{
		$dir = APPLICATION_DIR."/files/";

		if($sub_folder !="")
		{
			if(strpos($sub_folder,".") > 0 || strpos($sub_folder,"..") > 0 )
			{
				exit("File is not available");
			}
			$dir .= preg_replace("/;/", "/", $sub_folder);
		}

		if(strpos($rq_file_name,"."))
		{
			exit("File is not available");
		}

		$file_name = "";

		//check if file exist
		$dh = opendir($dir);

		while (($file = readdir($dh)) !== false) {

			if(md5($file) == "$rq_file_name")
			{
				$file_name = $file;
				break;
			}
		}
		closedir($dh);

		if($file_name == "")
		{
			exit("File is not available");
		}

		list($name,$extention) = explode(".",$file_name);

		$ctype="application/force-download";

		switch(strtolower($extention))
		{
			case "pdf": $ctype="application/pdf"; break;
			case "zip": $ctype="application/zip"; break;
			default: $ctype="application/octet-stream";
		}

		if ($fd = fopen ("$dir/$name.$extention", "r")) {
			$fsize = filesize("$dir/$name.$extention");

			header("Content-Type: $ctype");
			header("Content-Disposition: attachment; filename=\"".basename("$name.$extention")."\"");
			header("Content-length: $fsize");
			header("Cache-control: private"); //use this to open files directly

			while(!feof($fd)) {
				$buffer = fread($fd, 2048);
				echo $buffer;
			}
		}
		fclose ($fd);

		exit;
	}
}